<?php
/**
 * Created by PhpStorm.
 * User: happy
 * Date: 17/8/17
 * Time: 上午11:10
 */
class Server{
    private  $serv;
    public  function  __construct(){
        if(!function_exists('swoole_server_set')){
            echo 'no swoole module';
            return array('flag'=>false,'msg'=>'没有socket组件,swoole!');
        }

        $this->serv=new swoole_server('0.0.0.0',9501);
        $this->serv->set(array(
            'worker_num'=>2,
            'daemonize'=>false
        ));
        $this->serv->on('Start',array($this,'onStart'));
        $this->serv->on('Connect',array($this,'onConnect'));
        $this->serv->on('Receive',array($this,'onReceive'));
        $this->serv->on('close',array($this,'onClose'));
        $this->serv->start();
    }
    public  function  onStart($server){
        echo "start".chr(10);
    }
    public  function  onConnect($server,$fd,$from_id){
        $server->send($fd,'hello'.$fd);
    }
    public  function  onReceive(swoole_server $server,$fd,$from_id,$data){
        echo 'get message from client '.$fd.' '.$data;
        $server->send($fd,$data);
    }
    //
    public function  onClose($server,$fd,$from_id){
        echo 'client '.$fd.' close connection';
    }
}

$server=new Server();
